// pages/user-center/manage-team/create-team/create-team.js
const app = getApp();
const request = require('../../../../utils/request.js');
const config = require('../../../../utils/config.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    colorTheme: app.globalData.colorTheme,
    logoUrl: '',
    checkbox: [],
    choosedTagsIndex: [],
    choosedTagsName: []
  },

  /**
   * 服务器获取标签
   */
  showTagsModal: function (e) {
    let that = this;
    let choosedTagsIndex = that.data.choosedTagsIndex;
    let url = config.SERVER_URL + 'tags/listAllTags'
    wx.showLoading({
      title: '加载ing...'
    })
    request.requestGetApi(url, {}, {}, 'application/json').then(res => {
      if (res.status === config.STATUS_OK) {
        let allTags = res.data;
        for (let i = 0; i < choosedTagsIndex.length; i++) {
          allTags.find(function (value, index) {
            if (value.id == choosedTagsIndex[i]) {
              allTags[index]['checked'] = true;
            }
          });
        }
        this.setData({
          checkbox: allTags
        });
      }
    }).catch(err => {
      app.failFun(err)
    }).finally((res) => {
      app.completeFun(res)
    })
    this.showModal(e);
  },
  
  /**
   * 点中标签
   */
  chooseTag: function (e) {
    let id = e.currentTarget.dataset.value;
    let allTags = this.data.checkbox;
    let choosedTagsIndex = this.data.choosedTagsIndex;
    let choosedTagsName = this.data.choosedTagsName;
    allTags.find(function (value, index) {
      if (id == value.id) {
        allTags[index].checked = !allTags[index].checked;
        if (allTags[index].checked) {
          choosedTagsIndex.push(allTags[index].id);
          choosedTagsName.push(allTags[index].name);
        }else{
          choosedTagsIndex.pop();
          choosedTagsName.pop();
        }
        if (choosedTagsIndex.length > 3) {
          allTags[index].checked = false;
          choosedTagsIndex.pop();
          choosedTagsName.pop();
          wx.showModal({
            title: '提示',
            content: '标签数量不能 > 3',
          })
        }
      }
    });
    this.setData({
      checkbox: allTags,
      choosedTagsIndex: choosedTagsIndex,
      choosedTagsName: choosedTagsName
    })
  },

  /**
   *  标签模态框取消事件 
   */
  cancelChooseTags(){
    this.hideModal();
  },

  /**
   * 上传logo图片获取回传url
   */
  uploadLogoImage: function (e) {
    let token = wx.getStorageSync('token');
    let that = this;
    wx.chooseImage({
      success (res) {
        if(res.tempFiles.size > app.uploadFileMaxSize){
          wx.showToast({
            title: '上传文件不可超过11MB！',
            icon: 'none',
            duration: 1500
          });
          return;
        }
        const tempFilePaths = res.tempFilePaths;
        wx.showLoading({
          title: '上传ing'
        });
        wx.uploadFile({
          url: config.SERVER_URL + 'user/uploadImage',
          filePath: tempFilePaths[0],
          name: 'image',
          header: {
            'UT-Token': token
          },
          success (res) {
            if (res.statusCode != config.STATUS_OK) {
              app.failFun(res, that);
            }
            let obj = JSON.parse(res.data);
            that.setData({
              logoUrl: obj.data.filePath
            });
            wx.hideLoading();
          }
        })
      }
    })
  },

  /**
   * 提交创建团队表单
   */
  submitTeam(e){
    let params = e.detail.value;
    params.status = params.status ? 1 : 0;
    params.tagIds = this.data.choosedTagsIndex;
    params.logo = this.data.logoUrl;
    let msg = this.checkForm(params);
    if (msg) {
      wx.showModal({
        title: '提示',
        content: msg,
      })
      return;
    }
    let token = wx.getStorageSync('token');
    wx.showLoading({
      title: '创建中...'
    });
    let url = config.SERVER_URL + 'teams/createTeam';
    request.requestPostApi(url, token, params, 'application/json').then(res=>{
      if (res.status === config.STATUS_OK) {
        wx.navigateBack({
          delta: 1
        });
      }else{
        wx.showModal({
          title: '提示',
          content: res.message,
        })
      }
    }).catch((err) => {
      app.failFun(err);
    }).finally((res) => {
      app.completeFun(res);
    })
  },

   /**
   * 表单参数校验
   */
  checkForm: function(params){
    if (!params.logo){
      return '请设置团队logo';
    }
    if (!params.name) {
      return '请填写队名';
    }
    if (!params.tagIds.length) {
      return '请选择团队标签';
    }
    if (!params.description) {
      return '请填写团队描述';
    }
  },

  /**
   * 退出创建队伍界面提示
   */
  cancelEdit(){
    wx.showModal({
      title: '提示',
      content: '内容未保存，是否退出？',
      success (res) {
        if (res.confirm) {
          console.log(1);
        } else if (res.cancel) {
          console.log(2);
        }
      }
    });
  },

  /**
   * 模态框
   */
  showModal (e) {
    let modalName = e.currentTarget.dataset.target;
    if (modalName == 'Image') {
      this.setData({
        imageUrl: e.currentTarget.dataset.imageurl
      });
    }
    this.setData({
      modalName: modalName
    })
  },
  hideModal (e) {
    this.setData({
      modalName: null
    })
  },
})